package com.android.meige.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.meige.R;
import com.android.meige.SearchActivity;
import com.android.meige.activity.BaseObject;
import com.android.meige.activity.MainTab;
import com.android.meige.activity.mine.LoginActivity;
import com.android.meige.adapt.MainlistSquareAdapt;
import com.android.meige.model.group.MainSquareData;
import com.android.meige.model.group.MainSquareDataCallback;
import com.android.meige.utils.ConstantsUrl;
import com.android.meige.utils.HttpUtils;
import com.android.meige.utils.LoginState;
import com.android.meige.utils.MyLog;
import com.android.meige.utils.ObjectUtils;
import com.android.meige.view.recycleview.CustomLoadMoreView;
import com.android.meige.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static android.app.Activity.RESULT_OK;


/**
 * 海淘页
 */
public class Fragment3 extends Fragment implements BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;

    private FragmentActivity mcontext;
    private View view;
    private LayoutInflater inflater;
    private boolean networkConnected;
    private int page = 1;
    private MainlistSquareAdapt adapter;
    private LinearLayoutManager mLayoutManager;

    public Fragment3() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        this.inflater = inflater;
        view = inflater.inflate(R.layout.fragment_fragment3, container, false);
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        initUI();
        if (networkConnected) {
            GetDataListData(page);
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
        return view;
    }

    private void initUI() {
        initRecycle();
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
                switch (view.getId()) {
                    case R.id.item_list_square_thumb:
                        ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getExtension_id(), "");
                        break;
                }
                return false;
            }
        });

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                Intent intent_tuan = new Intent(mcontext, BaseObject.class);
                intent_tuan.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "团详情");
                intent_tuan.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, adapter.getItem(position).getCommon_id());
                mcontext.startActivity(intent_tuan);
            }
        });
        ReFreshData();
    }

    private void initRecycle() {
        adapter = new MainlistSquareAdapt(R.layout.item_list_square, null);
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == TO_REPLY) {
            progress.setVisibility(View.VISIBLE);
            page = 1;
            mRecyclerView.scrollToPosition(0);
            GetDataListData(page);
            mLayoutManager.scrollToPositionWithOffset(0, 0);
        }
    }

    private static final int TO_REPLY = 1;

    private void ReFreshData() {
        mRefreshLayout.setColorSchemeResources(R.color.app_title);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                if (networkConnected) {
                    page = 1;
                    GetDataListData(page);
                } else {
                    ObjectUtils.toast(mcontext, "网络连接出现异常");
                    mRefreshLayout.setRefreshing(false);
                }
            }
        });
    }

    //获取列表数据
    private void GetDataListData(final int page) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.MAIN_LISTDATA_SQUARE + "?page=" + page;
            MyLog.e("地址", address);
            HttpUtils.get(address, null, mCallback);
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mcontext, "网络连接出现异常");
            adapter.loadMoreFail();
        }
    }

    MainSquareDataCallback mCallback = new MainSquareDataCallback() {

        @Override
        public void onError(Call call, Exception e, int id) {
            mRefreshLayout.setRefreshing(false);
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
        }

        @Override
        public void onResponse(MainSquareData response, int id) {
            mRefreshLayout.setRefreshing(false);
            if (response == null) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                return;
            }
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            if (response.getCode() == 0) {
                MainSquareData.DataBean data = response.getData();
                if (data == null || !ObjectUtils.listHasData(data.getList())) {
                    if (page == 1) {
                        noData.setVisibility(View.VISIBLE);
                    } else {
                        adapter.loadMoreEnd();
                    }
                    return;
                }
                List<MainSquareData.DataBean.ListBean> list = data.getList();
                noData.setVisibility(View.GONE);
                if (page == 1) {
                    adapter.setNewData(list);
                } else {
                    adapter.addData(list);
                    adapter.loadMoreComplete();
                }
            } else {
                if (page == 1) {
                    noData.setVisibility(View.VISIBLE);
                    noDataTv.setText(response.getMsg());
                    noDataTv.setVisibility(View.VISIBLE);
                } else {
                    adapter.loadMoreFail();
                    ObjectUtils.toast(mcontext, response.getMsg());
                }
            }
        }
    };

    @OnClick({R.id.search_layout, R.id.update, R.id.click_resetnetwork_refresh})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_layout:
                Intent intent_search = new Intent(mcontext, SearchActivity.class);
                intent_search.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_SEARCH_TYPE, 1);
                startActivity(intent_search);
                break;
            case R.id.update:
                if (LoginState.getInstance().isLogin(mcontext)) {
                    Intent intent = new Intent(mcontext, MainTab.class);
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_ID, 1);
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_TYPE, 5);
                    startActivityForResult(intent, TO_REPLY);
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
                break;
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                page = 1;
                GetDataListData(page);
                break;
        }
    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetDataListData(page);
    }
}
